<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mindex extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
	
	public function checkUser($id)
	{
		$count = $this->db->query("SELECT id FROM score WHERE id = '".$id."' AND stop = 1")->num_rows();
		if($count == 0)
		{
			return 200;
		}
		return false;
	}
    
    public function checkCoin($id)
    {
        $coin = intval($this->db->query('SELECT content FROM setting WHERE type = "pay_coin_play" AND `active` = 1')->row_object()->content);
        
        $coin_user = $this->db->query('SELECT coin FROM user WHERE id = '.$id)->row_object()->coin;
        $c_user = $coin_user - $coin;
        if($c_user >= 0)
        {
            $codeTrade = 'GAME-'.date('YmdHis').'-'.$this->generateCode(8);
            $content = 'Thanh toán '.$coin.' Xu cho lần chơi ngày '.date('H:i:s d/m/Y').' <br />Mã giao dịch: ' .$codeTrade;
            
            $data = array('codeTrade' => $codeTrade, 'content' => $content, 'id_user' => $id, 'statusTrade' => 1, 'created' => date('Y-m-d H:i:s'));
            
            $this->db->insert('logTrade', $data);
            
            $this->db->update('user', array('coin' => $c_user), 'id ='.$id);
            $data_session = array('paymentPlay' => 1);
            $this->session->set_userdata($data_session);
            return 200;
        }else{
            
            $codeTrade = 'GAME-'.date('YmdHis').'-'.$this->generateCode(8);
            $content = 'Thanh toán thất bại '.$coin.' Xu cho lần chơi ngày '.date('H:i:s d/m/Y').'. <b>Mã thất bại:</b> thiếu tiền trong tài khoản. <br />Mã giao dịch: ' .$codeTrade;
            
            $data = array('codeTrade' => $codeTrade, 'content' => $content, 'id_user' => $id, 'statusTrade' => 0, 'created' => date('Y-m-d H:i:s'));
            
            $this->db->insert('logTrade', $data);
            
            return 500;
        }
        
    }
    
	public function noteUserDb($user_id)
	{
		$data = array(
			'user_id' => $user_id
		);
		
		$count = $this->db->query("SELECT id FROM score WHERE user_id = '".$user_id."'")->num_rows();
		if($count == 0)
		{
			$this->db->insert('score', $data);
		}
		return 200;
	}
	
	
	public function verifyAnswer($id_ques, $kq, $campaign, $id)
	{
	    $data = array(
			'user_id' => $id
		);
		
		$count = $this->db->query("SELECT id FROM score WHERE user_id = '".$id."'")->num_rows();
		if($count == 0)
		{
			$this->db->insert('score', $data);
		}
        
        $stop = $this->db->query("SELECT stop FROM score WHERE user_id = '".$id."'")->row_object()->stop;
        if($stop != 1)
        {
            $log = $this->db->query("SELECT id FROM logs WHERE id_ques = '".$id_ques."' AND user_id = '".$id."'")->num_rows();
            if($log == 0)
            {
                $this->updateLogDb($id, $id_ques);
                $answer = $this->db->query("SELECT answer FROM questions WHERE id = '".$id_ques."'")->row_object();
        		//die($answer->answer);
        		if($kq == $answer->answer)
        		{
        		    if($id_ques == 1)
                    {
                        $time_now = ($this->microtime_float() - 3000);    
                    }else{
                        $time_now = $this->microtime_float();
                    }
                    
        			$data_update = $this->updateScoreDb($time_now, $campaign, $id);
                    
                    $obj = (object)array('status' => 200, 'data' => $data_update);
        			return $obj;
        		}else{
        			$this->db->update('score', array('stop' => 1), "user_id = ".$id);
                    $obj = (object)array('status' => 201, 'data' => $answer->answer);
        			return $obj;
        		}   
            }
            $obj = (object)array('status' => 101, 'data' => '');
        			return $obj;
        }
        $obj = (object)array('status' => 100, 'data' => '');
        			return $obj;
		
	}
	
	private function updateScoreDb($time_now, $campaign, $id)
	{
		$data = $this->db->query("SELECT scores,time,answer FROM score WHERE user_id = '".$id."'")->row_array();
        $time_send = $this->db->query("SELECT time_send FROM time_send")->row_object()->time_send;
		$time = $time_now - $time_send;
        //die($time_now.'--'.$time_send);
        
		$score = $data['scores'] + 1;
		$timeup = $data['time'] + $time;
		
		$dataup = array(
			'scores' => $score,
			'time'   => $timeup,
            'answer' => $data['answer'] + 1,
		);
		
		$this->db->update('score', $dataup, "user_id = '".$id."'");
        
        /*
        $dataup['campaign_id'] = $campaign;
        $this->db->update('score_logs', $dataup, "user_id = '".$id."'");
        
        */ // Nhatnv comment lai vi khong dung cai nay nua la xong
        
        $session_reply = array('score' => $score, 'time' => $this->convertSecond($timeup));
        $this->session->set_userdata($session_reply);
        
		return (object)array('score' => $score, 'time' => $this->convertSecond($timeup));
		
	}
	private function updateLogDb($user_id,$id_ques)
    {
        $data = array(
            'user_id' => $user_id,
            'id_ques' => $id_ques,
            'click' => 1
        );
        $this->db->insert('logs', $data);
    }
	
	public function showResultsDb($id)
	{
		$_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        $data_ = $this->db->query('SELECT u.username, sl.scores, sl.time AS timet, u.fullname, sl.user_id FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id ORDER BY sl.scores DESC, sl.time ASC LIMIT 1')->row_object();
        if($id == $data_->user_id)
        {
            $data_->times = $this->convertSecond($data_->timet);
            return json_encode((object)array('bxh' => 1, 'data' => '<h2 style="text-align: center;color: #E70F31;font-size: 32px;">Xin chúc mừng, bạn là người thắng cuộc</h2><p style="text-align: center;">Bạn đã trả lời đúng '.$data_->scores.' câu hỏi trong thời gian '.$data_->times.'</p>'));
        }else{
            $data_user = $this->db->query('SELECT u.username, sl.scores, sl.timet, u.fullname FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id WHERE u.user_id = '.$id)->row_object();
            $data_user->times = $this->convertSecond($data_user->timet);
            return json_encode((object)array('bxh' => 2, 'data' => $data_user));
        }
        
	}
	
	public function finalResultsDb($id)
	{
		$data = $this->db->query("SELECT scores, time FROM score WHERE user_id = '".$id."'")->row_array();
        $data['time'] = $this->convertSecond($data['time']);
		return json_encode($data);
	}
    
    public function getBXH()
    {
        $_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        $data_ = $this->db->query('SELECT u.username, sl.scores, sl.time, u.fullname FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id ORDER BY sl.scores DESC, sl.time ASC LIMIT 10')->result_object();
        $html = '';
        foreach($data_ AS $el=>$le)
        {
            $name = '';
            $name = $le->fullname ? $le->fullname : $le->username;
            $html .= '<tr><td>'.($el+1).'.<a title="'.$name.'">'.$name.'</a></td>';
            $html .= '<td>'.$le->scores.'</td>';
            $html .= '<td>'.$this->convertSecond($le->time).'</td></tr>';
        }
        return (object)array('bxh' => $html);
    }
    
}
